package com.demo.a;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.ConsolePipeline;
import us.codecraft.webmagic.processor.PageProcessor;

/**
 * Created on 2016/11/15.
 */
public class Demo2 implements PageProcessor {

    private Site site = Site.me()
            .setDomain("my.oschina.net")
            .setCharset("utf-8")
            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36")
            .setRetryTimes(3)
            .setRetrySleepTime(1000);

    @Override
    public void process(Page page) {
        page.addTargetRequests(page.getHtml().links().regex("https://my\\.oschina\\.net/flashsword/blog/\\d+").all());
        page.addTargetRequests(page.getHtml().xpath("//div[@class='pages sm-hide']/ul/li/a").links().all());

        page.putField("title", page.getHtml().xpath("//div[@class='title']/text()"));
        page.putField("author", page.getHtml().xpath("//div[@class='name']/a/text()"));
        page.putField("content", null);

        if (page.getResultItems().get("title") == null || page.getResultItems().get("title").toString().trim().equals("")) {
            page.setSkip(true);
        }
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new Demo2())
                .addUrl("https://my.oschina.net/flashsword/blog")
                .addPipeline(new ConsolePipeline())
                .thread(5)
                .start();
    }
}
